package com.ygxsk.carhome.ui.usercenter;

import android.annotation.TargetApi;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.CustomWebView;
import com.ygxsk.carhome.views.ProgressView;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.CompositeDisposable;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-02-01  17:18
 * @Description:原始的webview加载器, 目前仅仅用来加载用户服务协议小界面。 android原生
 */
public class WebViewAboriginalActivity extends ErrorActivity implements ErrorParentExtraSingle {

    /**
     * 判断网页是否加载完全,默认是false
     */
    //private boolean loadError = false;

    /**
     * 监听器采集内容
     */
    private final CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    /**
     * 外侧的加载布局内容
     */
    //@BindView(R.id.loadingeasyinaboriginal)
    //LoadingLayout loadingEasyInAboriginal;

    @BindView(R.id.framelayoutwebinorgi)
    FrameLayout frameLayoutWebInorgi;

    private CustomWebView mWebView;

    //@BindView(R.id.refreshLayoutwebyuan)
    //com.scwang.smartrefresh.layout.SmartRefreshLayout refreshLayoutInWebNomal;


    /**
     * 从哪个界面跳转过来的 或者从哪个入口过来的 用户协议 或者 用户隐私政策
     */
    private int flag_jumpfrom_where;
    //------------------------------------------------------------------
    /**
     * 标识 用户协议的标识
     */
    public static final int HANDLER_ABORIGINA_FLAG = 203;

    /**
     * 标识用户协议的本地加载 标识
     */
    public static final int HANDLER_ABORIGINA_LOADLOCAL_FLAG = 2031;

    /**
     * 用户隐私政策的 加载标识
     */
    public static final int HANDLER_SECRECYTURL_FLAG = 204;
    //------------------------------------------------------------------

    /**
     * 添加本地的 隐私政策
     */
    public static final int HANDLER_SECRECYTURL_LOADLOCAL_FLAG = 2041;


    /**百度地图的隐私合规政策*/
    //private final int HANDLER_BAIDU_SECRECYTURL_FLAG = 205;

    /**
     * 用户位置使用协议的内容
     */
    private final int HANDLER_WHAT_LOCATIONARGEEN_FLAG = 206;

    /**
     * 更新进度条的标识
     */
    public static final int HANDLER_PROGRESS_FLAG = 213;

    /**
     * 处理用户协议的Handler
     */
    private static class BetterHandlerAborigina extends Handler {

        // ⚠ In Android, Handler classes should be static or leaks might occur.
        private final WeakReference<WebViewAboriginalActivity> mActivityInitialize;

        private BetterHandlerAborigina(WebViewAboriginalActivity _webViewAboriginalActivity, Looper looper) {
            super(looper);
            this.mActivityInitialize = new WeakReference<WebViewAboriginalActivity>(_webViewAboriginalActivity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            WebViewAboriginalActivity webViewAboriginalActivity = mActivityInitialize.get();

            if (webViewAboriginalActivity != null) {

                switch (msg.what) {

                    case HANDLER_ABORIGINA_FLAG: {//用户协议

                        //避开使用blankj
                        //method_load(Constants.getInstance().agreementPage()+"?name=" + AppUtils.getAppName());
                        //Log.d("itchen--地址信息为-->" ,Constants.getInstance().agreementPage() + "?name=" + CommUtils.getAppName(mActivityInstance));
                        //LogUtils.d("itchen----即将加载在线的 用户协议 文档");

                        // TODO: 2023-04-20 19:12 真实的应该是加载在线的协议文档
                        //webViewAboriginalActivity.method_loadUrl(ApiService.agreementPageUrl + Parameterkey.urlExtraName + CommUtils.getAppName(webViewAboriginalActivity));

                        webViewAboriginalActivity.method_loadUrl("file:///android_asset/useragreementl.html");

                        break;
                    }

                    case HANDLER_ABORIGINA_LOADLOCAL_FLAG: {//加载本地的 用户协议 内容

                        //LogUtils.d("itchen----即将加载本地的 用户协议 文档");
                        //String url = "file:///android_asset/useragreement.html";
                        webViewAboriginalActivity.method_loadUrl("file:///android_asset/useragreement.html");

                        break;
                    }

                    case HANDLER_SECRECYTURL_FLAG: {//隐私政策,加载在线文档

                        //LogUtils.d("itchen----即将加载在线的 隐私政策 文档");
                        // : 2023-04-20 19:12 真实的应该加载在线协议文档
                        //webViewAboriginalActivity.method_loadUrl(ApiService.secrecytUrl + Parameterkey.urlExtraName + CommUtils.getAppName(webViewAboriginalActivity));

                        webViewAboriginalActivity.method_loadUrl("file:///android_asset/privacyProtocolgj.html");

                        break;
                    }

                    case HANDLER_SECRECYTURL_LOADLOCAL_FLAG: {//隐私政策 本地加载的方法离线文档的html的

                        //LogUtils.d("itchen----即将加载本地的 隐私政策 文档");
                        //LogUtils.d("itchen----即将加载离线的 隐私政策 文档");
                        webViewAboriginalActivity.method_loadUrl("file:///android_asset/privacyProtocolgj.html");

                        break;
                    }

                    //--------------------------------------------------------------------------------------------

                    case HANDLER_PROGRESS_FLAG: {

                        if ((int) msg.obj == 100) {
                            //加载完毕进度条消失
                            if (webViewAboriginalActivity.progressView != null) {
                                webViewAboriginalActivity.progressView.setVisibility(View.GONE);
                            }
                        } else {
                            //更新进度
                            if (webViewAboriginalActivity.progressView != null) {
                                webViewAboriginalActivity.progressView.setVisibility(View.VISIBLE);
                                webViewAboriginalActivity.progressView.setProgress((int) msg.obj);
                            }
                        }
                        break;
                    }

                    default:
                        break;
                }
            }
        }
    }

    private ProgressView progressView;//进度条
    private BetterHandlerAborigina handlerAborigina;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        processExtraData();

        if (handlerAborigina == null) {
            handlerAborigina = new BetterHandlerAborigina(this, Looper.getMainLooper());
        }

        initloading();

        initViews();

        gainDatas();

    }

    @Override
    public Resources getResources() {
        return super.getResources();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mWebView != null) {
            mWebView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWebView != null) {
            mWebView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }

        if (handlerAborigina != null) {
            handlerAborigina.removeCallbacksAndMessages(null);
        }

        if (progressView != null) {
            progressView = null;
        }


        if (mWebView != null) {

            //destory()
            ViewParent parent = mWebView.getParent();

            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }

            mWebView.stopLoading();
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            //WebView.clearView()在api18以后被废弃,可以使用WebView.loadUrl(“about:blank”)代替
            //mWebView.clearView();
            mWebView.loadUrl("about:blank");
            mWebView.removeAllViews();

            mWebView.setVisibility(View.GONE);

            mWebView.destroy();

            mWebView = null;

            if (frameLayoutWebInorgi != null) {
                frameLayoutWebInorgi = null;
            }

//            ThreadUtils.executeBySingleWithDelay(new ThreadUtils.SimpleTask<Void>() {
//
//                @Override
//                public Void doInBackground() throws Throwable {
//
//                    // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
//                    // destory()
//                    ViewParent parent = mWebView.getParent();
//
//                    if (parent != null) {
//                        ((ViewGroup) parent).removeView(mWebView);
//                    }
//
//                    mWebView.stopLoading();
//                    mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
//                    // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
//                    mWebView.getSettings().setJavaScriptEnabled(false);
//                    mWebView.clearHistory();
//                    //WebView.clearView()在api18以后被废弃,可以使用WebView.loadUrl(“about:blank”)代替
//                    //mWebView.clearView();
//                    mWebView.loadUrl("about:blank");
//                    mWebView.removeAllViews();
//
//                    mWebView.setVisibility(View.GONE);
//
//                    mWebView.destroy();
//
//                    mWebView = null;
//
//                    if (frameLayoutWebInorgi != null) {
//                        frameLayoutWebInorgi = null;
//                    }
//
//                    return null;
//                }
//
//                @Override
//                public void onSuccess(Void result) {
//
//                }
//            }, 1000, TimeUnit.MILLISECONDS);

        }

        if (frameLayoutWebInorgi != null) {
            frameLayoutWebInorgi.removeAllViews();
            //frameLayoutWebInorgi = null;
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_web_view_aboriginal;
    }


    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        processExtraData();

        if (flag_jumpfrom_where == ExtraValue.WHAT_TEXTAGREEMENTURL//用户协议加载在线文档
                || flag_jumpfrom_where == ExtraValue.WHAT_TEXTAGREEMENTURL_LOADLOCAL) {//用户协议加载离线文档
            toolbarHelper.setTitle(getString(R.string.textserviceagreement));
        } else if (flag_jumpfrom_where == ExtraValue.WHAT_TEXTSECRECYTURL//隐私政策加载在线文档的
                || flag_jumpfrom_where == ExtraValue.WHAT_TEXTSECRECYTURL_LOADLOCAL) {//隐私政策加载离线文档的
            toolbarHelper.setTitle(getString(R.string.textprivacypolicy));
        }

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        //2022年8月6日13:24:44之前是没有关闭叉号的，但现在因为有【隐私政策】的链接，避免出现用户点击太深无法关闭；
        //toolbarHelper.setLayoutClose(false, "", null);
        //如果是【隐私政策】过来的，出现叉号，如果是【用户协议】过来的没有叉号
        if (flag_jumpfrom_where == ExtraValue.WHAT_TEXTSECRECYTURL//如果是【隐私政策】加载在线文档的
                || flag_jumpfrom_where == ExtraValue.WHAT_TEXTSECRECYTURL_LOADLOCAL) {//隐私政策加载离线文档的

            toolbarHelper.setLayoutClose(true, "", new ClickUtils.OnDebouncingClickListener() {

                @Override
                public void onDebouncingClick(View v) {

                    //直接关闭、杀死该界面；
                    if (!mActivityInstance.isFinishing()) {
                        mActivityInstance.finish();
                    }

                }
            });

        } else if (flag_jumpfrom_where == ExtraValue.WHAT_TEXTAGREEMENTURL//如果是【用户协议】过来的加载在线文档的
                || flag_jumpfrom_where == ExtraValue.WHAT_TEXTAGREEMENTURL_LOADLOCAL) {//用户协议加载离线文档的

            toolbarHelper.setLayoutClose(true, "", new ClickUtils.OnDebouncingClickListener() {

                @Override
                public void onDebouncingClick(View v) {
                    //直接关闭该页面
                    if (!mActivityInstance.isFinishing()) {
                        mActivityInstance.finish();
                    }
                }
            });

        } else {

            toolbarHelper.setLayoutClose(false, "", null);

        }

        toolbarHelper.setLayoutRight(false, 0, "", null);

        // TODO: 2023-07-04 16:38 添加一个切换环境的方法
//        toolbarHelper.getTitleTextView().setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//
//                CommUtils.method_open(mSession, mActivityInstance);
//
//                return true;
//            }
//        });

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                .statusBarColor(R.color.white)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void onClickNodata(View v) {

        findWebView();

        /*if (refreshLayoutInWebNomal != null) {
            refreshLayoutInWebNomal.setEnableRefresh(true);
        }*/

        gainDatas();

    }

    private void findWebView() {

        if (mWebView != null) {

            mWebView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);

                    mWebView.getSettings().setBlockNetworkImage(false);

                    //retain
                    //LogUtils.d("itchen---onPageStarted-->"+url);

                }


                //加载报错内容
                @Override
                public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                    super.onReceivedError(view, request, error);


                }

                //Android6.0以上判断404或者500：
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                    super.onReceivedHttpError(view, request, errorResponse);

                }

                @Nullable
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    //public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

                    if (!TextUtils.isEmpty(url)) {

                        if (url.startsWith("http") || url.startsWith("https")) {
                            view.loadUrl(url);
                        } else {
                            //LogUtils.d("itchen---->出现了 【非http】 或者 【非https协议】");
                        }

                    } else {
                        netWorkError();
                        //finishRefresh(refreshLayoutInWebNomal);
                    }

                    return true;
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);

                    mWebView.getSettings().setBlockNetworkImage(false);

                    //LogUtils.d("itchen---onPageFinished-->"+url);

                    loadingGone();

                    /*if (loadingEasyInAboriginal != null) {
                        loadingEasyInAboriginal.showContent();
                    }*/

                    //finishRefresh(refreshLayoutInWebNomal);

                    //if (refreshLayoutInWebNomal != null) {
                    //refreshLayoutInWebNomal.setEnableRefresh(false);
                    //}

                    //setEnableLoadmore(refreshLayoutInWebNomal,false);
                    //LogUtils.d("itchen--用户协议加载完毕----onPageFinished--" + url);
                    //itchen--用户协议加载完毕----onPageFinished--http://wuyeapi.91dgj.com//app/html/agreement/agreementPage.html
                    //    itchen--用户协议加载完毕----onPageFinished--
                    // http://wuyeapi.91dgj.com//app/html/helpPage.html?userToken=0e21d574de4e466e585017af701f261c

                }

                /*@Override
                public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
                    //super.doUpdateVisitedHistory(view, url, isReload);
                    if (needClearHistory) {
                        webView.clearHistory();
                        needClearHistory = false;
                    }
                }*/


            });


            mWebView.setWebChromeClient(new WebChromeClient() {

                @Override
                public void onProgressChanged(WebView view, int newProgress) {

                    if (handlerAborigina != null) {
                        sendMsg(handlerAborigina, HANDLER_PROGRESS_FLAG, newProgress);
                    }
                    super.onProgressChanged(view, newProgress);
                }

            });

        }

    }

    @Override
    protected void initViews() {

        //webView内容
        //==========================================================================================
        getWindow().setFormat(PixelFormat.TRANSLUCENT);

        mWebView = new CustomWebView(WebViewAboriginalActivity.this);
        progressView = new ProgressView(WebViewAboriginalActivity.this);


        //自己手动修改
        final float scale = WebViewAboriginalActivity.this.getResources().getDisplayMetrics().density;
        //int reslut = (int) (dpValue * scale + 0.5f);
        int reslut = (int) (2 * scale + 0.5f);

        progressView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, reslut));//dp2px(context, 4)));

        //progressView.setColor(ColorUtils.getColor(R.color.progresscol));
//        progressView.setColor(Color.parseColor("#31CE15"));
//        progressView.setColor(Color.parseColor(getResources().getColor(R.color.redcomm)));
        progressView.setColor(ContextCompat.getColor(this, R.color.redcomm));

        progressView.setProgress(10);

        //progressView.setPadding(-30,0,10,0);

        //把进度条加到Webview中
        mWebView.addView(progressView);


        //加载页面
        //=================================================================================================
        //WebSettings webSetting = mWebView.getSettings();
        //mWebView.clearCache(true);//手动清空缓存内容。

        //加载页面
        mWebView.requestFocus();//触摸焦点起作用、
        mWebView.setVerticalScrollBarEnabled(false);//取消Vertical ScrollBar显示
        mWebView.setHorizontalScrollBarEnabled(false); //取消Horizontal ScrollBar显示

        CommUtils.setWebViewNomal(this, mWebView);

        //暂时没有
        //mWebView.addJavascriptInterface(getHtmlObject(), "Android");

        frameLayoutWebInorgi.setVerticalFadingEdgeEnabled(false);
        frameLayoutWebInorgi.setVerticalScrollBarEnabled(false);
        frameLayoutWebInorgi.setHorizontalScrollBarEnabled(false);

        frameLayoutWebInorgi.addView(mWebView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));

        //设置左右间距，因为原版的网页右侧间隙较大 2020-7-13 14:28:16
        //frameLayoutWebInorgi.setPadding(30,0,10,0);

        findWebView();

    }

    private void method_loadUrl(String h5url) {

        if (!TextUtils.isEmpty(h5url)) {

            //LogUtils.d("itchen-----详情页--执行method_loadUrl");
            if (mWebView != null) {
                mWebView.loadUrl(h5url);
            }

        } else {

            //LogUtils.d("itchen-----详情页--执行method_loadUrl 报错-");

            netWorkError();

        }

    }

    /**
     * 最终销毁webView
     */
    private void clearHistory() {

        if (mWebView != null) {
            mWebView.clearHistory();
            mWebView.clearCache(true);
        }

    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {

            if (flag_jumpfrom_where == ExtraValue.WHAT_TEXTAGREEMENTURL) {//用户协议,加载在线文档，

                sendMsg(handlerAborigina, HANDLER_ABORIGINA_FLAG, "");

            } else if (flag_jumpfrom_where == ExtraValue.WHAT_TEXTAGREEMENTURL_LOADLOCAL) {//用户协议，加载本地文档

                sendMsg(handlerAborigina, HANDLER_ABORIGINA_LOADLOCAL_FLAG, "");

            } else if (flag_jumpfrom_where == ExtraValue.WHAT_TEXTSECRECYTURL) {//隐私政策，加载在线文档的

                sendMsg(handlerAborigina, HANDLER_SECRECYTURL_FLAG, "");

            } else if (flag_jumpfrom_where == ExtraValue.WHAT_TEXTSECRECYTURL_LOADLOCAL) {//隐私政策，加载本地文档

                sendMsg(handlerAborigina, HANDLER_SECRECYTURL_LOADLOCAL_FLAG, "");

            }

        } else {

            netWorkError();

        }

    }

    @Override
    protected void methodBack() {

        if (mWebView != null) {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
            } else {

                if (ActivityUtils.isActivityAlive(WebViewAboriginalActivity.this)) {
                    ActivityUtils.finishActivity(WebViewAboriginalActivity.this);
                }

            }

        } else {
            if (ActivityUtils.isActivityAlive(WebViewAboriginalActivity.this)) {
                ActivityUtils.finishActivity(WebViewAboriginalActivity.this);
            }
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (mWebView != null) {

                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                    return true;
                }

            } else {
                //消息推送的跳转内容
                //isAdvBack();
                if (ActivityUtils.isActivityAlive(WebViewAboriginalActivity.this)) {
                    ActivityUtils.finishActivity(WebViewAboriginalActivity.this);
                }

            }

        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void processExtraData() {

        //是从哪里跳转过来的
        Bundle extras_bundle = this.getIntent().getExtras();

        if (extras_bundle != null) {

            flag_jumpfrom_where = extras_bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE, 0);

        }

    }
}
